package com.he.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.he.dao.HotelDao;
import com.he.entity.City;
import com.he.entity.Hotel;
import com.he.entity.ResultData;
import com.he.entity.Room;
import com.he.event.constact.EventConstact;
import com.he.event.util.EventUtil;
import com.he.feign.CityFeign;
import com.he.service.IHotelService;
import com.he.service.IRoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

@Service
public class HotelServiceImpl extends ServiceImpl<HotelDao,Hotel> implements IHotelService {
    @Autowired
    private CityFeign cityFeign;

    @Autowired
    private HotelDao hotelDao;

    @Autowired
    private IRoomService roomService;

    @Autowired
    private EventUtil eventUtil;

    /**
     * 保存酒店信息
     * @param entity
     * @return
     */
    @Override
    public boolean save(Hotel entity) {
        boolean flag = super.save(entity);
        //调用城市服务，修改城市对应的酒店数量
        cityFeign.updateCityHNumber(entity.getCid(), 1);
        eventUtil.publishEvent(EventConstact.EVENT_HOTEL_INSERT,entity);
        return flag;
    }

    /**
     * 查询酒店列表
     * @return
     */
    @Override
    public List<Hotel> list() {
        List<Hotel> hotels = super.list();
        for (Hotel hotel : hotels) {
            //获得酒店对应的城市id
            Integer cid = hotel.getCid();
            //获得城市对象
            ResultData<City> cityResultData = cityFeign.queryName(cid);
            //设置城市对象
            hotel.setCity(cityResultData.getData());
            //获得客房信息
            QueryWrapper wrapper = new QueryWrapper<>()
                    .eq("hid", hotel.getId());
            List<Room> rooms = roomService.list(wrapper);
            hotel.setRooms(rooms);
        }
        return hotels;
    }

    @Override
    public Hotel getHotelByHid(Integer hid) {
        return hotelDao.getHotelByHid(hid);
    }

    /**
     * 查询酒店信息 - 根据id
     * @param id
     * @return
     */
    @Override
    public Hotel getById(Serializable id) {
        Hotel hotel = super.getById(id);

        //获得酒店对应的城市id
        Integer cid = hotel.getCid();
        //获得城市对象
        ResultData<City> cityResultData = cityFeign.queryName(cid);
        //设置城市对象
        hotel.setCity(cityResultData.getData());

        //获得客房信息
        QueryWrapper wrapper = new QueryWrapper<>()
                .eq("hid", hotel.getId());
        List<Room> rooms = roomService.list(wrapper);
        hotel.setRooms(rooms);

        return hotel;
    }
}
